function sd = frac2serial(fd)
%frac2serial - fractional year to MATLAB serial date conversion
%
%       SD = frac2serial(FD)
%
% If FD is a vector of dates expressed in standard decimal part of a year 
% (e.g., 2-Jan-2005 is 2005+1/365 = 2005.00274), this function provides 
% the corresponding date vector MJD expessed in MATLAB serial date form,
% i.e. the date provided by datenum function.  
% The leap year case is automatically taken into account. 
% Please note that meaningless results are obtained if the date is BCE.  
%
% See also date2gpsw, gpsw2serial, serial2frac, frac2MJD, MJD2frac, 
% serial2YMD, leapy.

% G. Teza, 2021

fd = fd(:);             % to have a column vector

ud = fix(fd);
ed = fd-ud;             % Decimal part of the year

nr = size(fd,1);        % #rows   

Ily = leapy(ud);        % is 1 (logical) for leapy years
moltfact = 365*ones(nr,1);
moltfact(Ily) = 366;

nj = round(ed.*moltfact);           % "+1" is necessary to avoid the "0 day case" 

dtj = datetime([ud ones(nr,2)]);    % datetime object

sd = datenum(dtj)+nj;